from django.db.models import Q
from django.shortcuts import (
    render, redirect
)
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt

from sales import models
from sales.my_forms import CustomerForm


# Create your views here.


def home(request):
    return render(request, 'salaeshtml/home.html')


class CustomerView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, request):

        current_request_path = request.path
        print(current_request_path)
        if current_request_path == reverse('customers'):
            tag = 1
            customer_list = models.Customer.objects.filter(consultant__isnull=True)
        else:
            tag = 2
            # user_obj = models.UserInfo.objects.get(id=request.session.get('user_id'))
            user_obj = request.user_obj
            customer_list = models.Customer.objects.filter(consultant=user_obj)
        try:
            page_num = abs(int(request.GET.get('page', 1)))
            page_num = 1 if page_num <= 0 else page_num
        except Exception as e:
            page_num = 1
        kw = request.GET.get('kw')
        search_field = request.GET.get('search_field')
        if kw:
            kw = kw.strip()
            q_obj = Q()
            q_obj.children.append((search_field, kw))  # Q(name=kw)
            # customer_list = models.Customer.objects.filter(**{search_field: kw})
            customer_list = customer_list.filter(q_obj)
        else:
            kw = ''
            customer_list = customer_list
        per_page_num = 10  # 每页显示10条
        customer_count = customer_list.count()
        shang, yu = divmod(customer_count, per_page_num)

        if yu:
            page_num_count = shang + 1
        else:
            page_num_count = shang
        if page_num >= page_num_count:
            page_num = page_num_count
        # 页面生成页码的数量
        page_num_show = 5
        half_show = page_num_show // 2
        if page_num - half_show > 0:
            start_page_num = page_num - half_show
            end_page_num = page_num + half_show + 1
        else:
            start_page_num = 1
            end_page_num = 6
        if end_page_num >= page_num_count:
            end_page_num = page_num_count + 1
            start_page_num = end_page_num - page_num_show
        if page_num_count <= page_num_show:
            start_page_num = 1
            end_page_num = page_num_count + 1
        page_num_range = range(start_page_num, end_page_num)
        page_html = ''
        page_pre_html = f"""
            <nav aria-label="Page navigation">
                <ul class="pagination">
                                <li>
                        <a href="{current_request_path}?search_field={search_field}&kw={kw}&page={1}" aria-label="Next">
                            <span aria-hidden="true">首页</span>
                        </a>
                    </li>
                    <li>
                        <a href="{current_request_path}?search_field={search_field}&kw={kw}&page={page_num - 1}" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
            """
        page_html += page_pre_html
        for i in page_num_range:
            if page_num == i:
                page_html += f'<li class="active"><a href="{current_request_path}?search_field={search_field}&kw={kw}&page={i}">{i}</a></li>'
            else:
                page_html += f'<li><a href="{current_request_path}?search_field={search_field}&kw={kw}&page={i}">{i}</a></li>'
        page_next_html = f"""
                        <li>
                        <a href="{current_request_path}?search_field={search_field}&kw={kw}&page={page_num + 1}" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    <li>
                        <a href="{current_request_path}?search_field={search_field}&kw={kw}&page={page_num_count}" aria-label="Next">
                            <span aria-hidden="true">尾页</span>
                        </a>
                    </li>
                </ul>
            </nav>
            """
        page_html += page_next_html
        try:
            customer_obj = customer_list[(page_num - 1) * per_page_num: page_num * per_page_num]
        except Exception:
            customer_obj = customer_list
        return render(request, 'salaeshtml/custormers.html',
                      {'customer_obj': customer_obj, 'page_html': page_html, 'kw': kw,
                       'search_field': search_field.strip() if search_field else '',
                       'current_request_path': current_request_path, 'tag': tag})

    def post(self, request):
        action = request.POST.get('action')
        cids = request.POST.getlist('cids')
        if hasattr(self, action):
            customers = models.Customer.objects.filter(pk__in=cids)
            getattr(self, action)(request, customers)
            return redirect(request.path)

    # 公转私
    def reverse_gs(self, request, customers):
        customers.update(consultant_id=request.session.get('user_id'))

    # 私转公
    def reverse_sg(self, request, customers):
        customers.update(consultant=None)


def customers(request):
    current_request_path = request.path
    print(current_request_path)
    if current_request_path == reverse('customers'):
        customer_list = models.Customer.objects.filter(consultant__isnull=True)
    else:
        user_obj = models.UserInfo.objects.get(id=request.session.get('user_id'))
        customer_list = models.Customer.objects.filter(consultant=user_obj)
    try:
        page_num = abs(int(request.GET.get('page', 1)))
        page_num = 1 if page_num <= 0 else page_num
    except Exception as e:
        page_num = 1
    kw = request.GET.get('kw')
    search_field = request.GET.get('search_field')
    if kw:
        kw = kw.strip()
        q_obj = Q()
        q_obj.children.append((search_field, kw))  # Q(name=kw)
        # customer_list = models.Customer.objects.filter(**{search_field: kw})
        customer_list = customer_list.filter(q_obj)
    else:
        kw = ''
        customer_list = customer_list
    per_page_num = 10  # 每页显示10条
    customer_count = customer_list.count()
    shang, yu = divmod(customer_count, per_page_num)

    if yu:
        page_num_count = shang + 1
    else:
        page_num_count = shang
    if page_num >= page_num_count:
        page_num = page_num_count
    # 页面生成页码的数量
    page_num_show = 5
    half_show = page_num_show // 2
    if page_num - half_show > 0:
        start_page_num = page_num - half_show
        end_page_num = page_num + half_show + 1
    else:
        start_page_num = 1
        end_page_num = 6
    if end_page_num >= page_num_count:
        end_page_num = page_num_count + 1
        start_page_num = end_page_num - page_num_show
    if page_num_count <= page_num_show:
        start_page_num = 1
        end_page_num = page_num_count + 1
    page_num_range = range(start_page_num, end_page_num)
    page_html = ''
    page_pre_html = f"""
    <nav aria-label="Page navigation">
        <ul class="pagination">
                        <li>
                <a href="{current_request_path}?search_field={search_field}&kw={kw}&page={1}" aria-label="Next">
                    <span aria-hidden="true">首页</span>
                </a>
            </li>
            <li>
                <a href="{current_request_path}?search_field={search_field}&kw={kw}&page={page_num - 1}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
    """
    page_html += page_pre_html
    for i in page_num_range:
        if page_num == i:
            page_html += f'<li class="active"><a href="{current_request_path}?search_field={search_field}&kw={kw}&page={i}">{i}</a></li>'
        else:
            page_html += f'<li><a href="{current_request_path}?search_field={search_field}&kw={kw}&page={i}">{i}</a></li>'
    page_next_html = f"""
                <li>
                <a href="{current_request_path}?search_field={search_field}&kw={kw}&page={page_num + 1}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
            <li>
                <a href="{current_request_path}?search_field={search_field}&kw={kw}&page={page_num_count}" aria-label="Next">
                    <span aria-hidden="true">尾页</span>
                </a>
            </li>
        </ul>
    </nav>
    """
    page_html += page_next_html
    try:
        customer_obj = customer_list[(page_num - 1) * per_page_num: page_num * per_page_num]
    except Exception:
        customer_obj = customer_list
    return render(request, 'salaeshtml/custormers.html',
                  {'customer_obj': customer_obj, 'page_html': page_html, 'kw': kw,
                   'search_field': search_field.strip() if search_field else '',
                   'current_request_path': current_request_path})


@csrf_exempt
def add_edit_customer(request, cid=None):
    """
    添加和编辑客户
    :param request:
    :param cid: 客户id
    :return:
    """
    customer_obj = models.Customer.objects.filter(pk=cid).first()
    # print(request.get_full_path())
    next_path = request.get_full_path().split('=', maxsplit=1)[-1]
    # print(next_path)
    # print('GET***+**', request.GET)

    if request.method == 'GET':
        customer_form = CustomerForm(instance=customer_obj)
        return render(request, 'salaeshtml/edit_customer.html', {'customer_form': customer_form})
    else:
        customer_form = CustomerForm(data=request.POST, instance=customer_obj)
        if customer_form.is_valid():
            customer_form.save()
            # return redirect(next_path, kw=kw)
            return redirect(next_path)
        return render(request, 'salaeshtml/add_customer.html', {'customer_form': customer_form})
